<template>
  <div class="password_container">
    <!--卡片视图-->
    <el-card>
      <!--搜索栏-->
      <el-row :gutter="24">
        <el-col :span="7">
          <el-button type="primary" @click="show.addDialogVisible = true">添加密码</el-button>
        </el-col>
        <el-col :span="17">
          <el-input v-model="queryInfo.query" placeholder="请输入内容" clearable>
            <el-button slot="append" icon="el-icon-search" @click="queryList"></el-button>
          </el-input>
        </el-col>
      </el-row>
      <!--用户密码区域-->
      <el-table stripe border :data="passwordList" style="width: 100%; margin-top: 10px">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="title" label="标题"></el-table-column>
        <el-table-column prop="comment" label="描述"></el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="showEditDialog(scope.row.id)" icon="el-icon-edit"></el-button>
            <el-button type="warning" size="mini" @click="showPasswordDialog(scope.row.id)" icon="el-icon-setting"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页区域-->
      <el-pagination
        small
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-size="queryInfo.pageSize"
        layout="total,prev,next,jumper"
        :total="queryInfo.total">
      </el-pagination>
    </el-card>

    <!--修改用户的对话框-->
    <el-dialog title="修改密码" :visible.sync="show.editDialogVisible" width="90%" @close="editDialogClosed">
      <!--内容主体区域 ref引用名称 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="标题" label-width="120px" prop="title">
          <el-input v-model="editForm.title"></el-input>
        </el-form-item>
        <el-form-item label="访问地址" label-width="120px" prop="url">
          <el-input v-model="editForm.url"></el-input>
        </el-form-item>
        <el-form-item label="用户名" label-width="120px" prop="username">
          <el-input v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="描述" label-width="120px" prop="comment">
          <el-input v-model="editForm.comment"></el-input>
        </el-form-item>
      </el-form>
      <!--底部按钮区域-->
      <div slot="footer" class="dialog-footer">
        <el-button style="position: absolute;left: 20px" type="danger" @click="deletePassword">删 除</el-button>
        <el-button @click="show.editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editPassword">确 定</el-button>
      </div>
    </el-dialog>

    <!--添加用户的对话框-->
    <el-dialog title="新增密码" :visible.sync="show.addDialogVisible" width="90%" @close="addDialogClosed">
      <!--内容主体区域 ref引用名称 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="标题" label-width="120px" prop="title">
          <el-input v-model="addForm.title"></el-input>
        </el-form-item>
        <el-form-item label="访问地址" label-width="120px" prop="url">
          <el-input v-model="addForm.url"></el-input>
        </el-form-item>
        <el-form-item label="用户名" label-width="120px" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="120px" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="描述" label-width="120px" prop="comment">
          <el-input v-model="addForm.comment"></el-input>
        </el-form-item>
      </el-form>
      <!--底部按钮区域-->
      <div slot="footer" class="dialog-footer">
        <el-button @click="show.addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addPassword">确 定</el-button>
      </div>
    </el-dialog>

    <!--获取用户密码的对话框-->
    <el-dialog title="密码" :visible.sync="show.passwordDialogVisible" width="90%" @close="passwordDialogClosed">
      <!--内容主体区域 ref引用名称-->
      <el-form :model="passwordForm" :rules="passwordFormRules"  ref="passwordFormRef">
        <el-form-item label="开发者号码" label-width="100px" prop="phone">
          <el-input v-model="passwordForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="验证码" label-width="100px" prop="verifyCode">
          <div style="display: flex"><el-input v-model="passwordForm.verifyCode"></el-input><img class="v_img" :src="passwordForm.captcha"/></div>
        </el-form-item>
      </el-form>
      <!--底部按钮区域-->
      <div slot="footer" class="dialog-footer">
        <el-button @click="show.passwordDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="getPassword">获取密码</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入加密传输工具
import { Enc } from '../../utils/secret'

export default {
  name: 'Password',
  data () {
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 12,
        total: 0
      },
      show: {
        addDialogVisible: false,
        editDialogVisible: false,
        passwordDialogVisible: false
      },
      passwordForm: {
        captcha: '',
        verifyCode: ''
      },
      passwordFormRules: {
        phone: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入11位手机号码', trigger: 'blur' },
          {
            pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
            message: '请输入正确的手机号码'
          }
        ],
        verifyCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { min: 4, max: 4, message: '验证码长度为4', trigger: 'blur' }
        ]
      },
      addForm: {},
      addFormRules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '请输入地址', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 20, message: '昵称的长度在2~20个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码的长度在6~20个字符之间', trigger: 'blur' }
        ]
      },
      editForm: {},
      editFormRules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '请输入地址', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 20, message: '昵称的长度在2~20个字符之间', trigger: 'blur' }
        ]
      },
      passwordList: []
    }
  },
  created () {
    this.getPasswordList()
  },
  methods: {
    async getPasswordList () {
      try {
        const { data: res } = await this.$http.post('/ajshow/password/list', this.queryInfo)
        if (!res.status) return this.$message.error(res.msg ? res.msg : '获取用户密码信息异常')
        this.passwordList = res.data
        this.queryInfo.total = res.total
      } catch (e) {
        this.$message.error(e.toString())
      }
    },
    handleCurrentChange (newPage) {
      this.queryInfo.pageNum = newPage
      this.getPasswordList()
    },
    queryList () {
      this.queryInfo.pageNum = 1
      this.getPasswordList()
    },
    async showEditDialog (id) {
      try {
        const { data: res } = await this.$http.post('/ajshow/password/detail/' + id)
        if (!res.status) return this.$message.error('查询密码详细数据失败')
        this.editForm = res.data
        this.show.editDialogVisible = true
      } catch (e) {
        console.log(e.toString())
        return this.$message.error('获取详细信息异常')
      }
    },
    // 监听修改用户对话框关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 监听新增用户对话框关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 监听查看密码对话框关闭事件
    passwordDialogClosed () {
      this.$refs.passwordFormRef.resetFields()
    },
    // 点击修改用户
    editPassword () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return this.$message.error('验证不通过')
        // 发起修改用户的真正请求
        const { data: res } = await this.$http.put('/ajshow/password/update', this.editForm)
        if (!res.status) return this.$message.error('修改密码失败')
        this.$message.success('修改密码成功')
        // 隐藏添加用户的对话框
        this.show.editDialogVisible = false
        // 刷新用户列表
        this.getPasswordList()
      })
    },
    // 点击删除用户
    async deletePassword () {
      // 这样就不需要加 async 和 await
      const confirmResult = await this.$confirm('此操作将永久删除该密码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 确认删除 confirm 取消异常 cancel
      if (confirmResult !== 'confirm') return this.$message.info('用户取消了删除')
      // 发起删除用户的真正请求
      const { data: res } = await this.$http.post('/ajshow/password/delete', this.editForm)
      if (!res.status) return this.$message.error('删除密码失败')
      this.$message.success('删除密码成功')
      // 隐藏添加用户的对话框
      this.show.editDialogVisible = false
      // 刷新用户列表
      this.getPasswordList()
    },
    // 点击添加用户
    addPassword () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('验证不通过')
        const loading = this.$loading({
          lock: true,
          text: '添加密码中',
          customClass: 'iconfont icon-jiazai2',
          background: 'rgba(0, 0, 0, .7)'
        })
        try {
          // 第一步获取密钥:参数加密传输
          const { data: enKey } = await this.$http.post('/ajshow/auth/getEncKey')
          if (!enKey.status) {
            loading.close()
            return this.$message.warning('初始化第一次连接')
          }
          // 发起修改用户的真正请求
          const { data: res } = await this.$http.post('/ajshow/password/add', {
            title: this.addForm.title,
            url: this.addForm.url,
            username: Enc(this.addForm.username, enKey.data),
            password: Enc(this.addForm.password, enKey.data),
            comment: this.addForm.comment
          })
          if (!res.status) {
            loading.close()
            return this.$message.error('添加密码失败')
          }
          this.$message.success('添加密码成功')
          // 隐藏添加用户的对话框
          this.show.addDialogVisible = false
          // 刷新用户列表
          this.getPasswordList()
        } catch (e) {
          this.$message.error(e.toString())
        }
        loading.close()
      })
    },
    async showPasswordDialog (id) {
      this.passwordForm.id = id
      const { data: res } = await this.$http.get('/ajshow/auth/captcha/' + 100 + '/' + 30 + '/' + id)
      if (!res.status) return this.$message.error('获取验证码失败')
      this.passwordForm.captcha = res.data
      this.show.passwordDialogVisible = true
    },
    async getPassword () {
      this.$refs.passwordFormRef.validate(async valid => {
        if (!valid) return this.$message.error('验证不通过')
        const loading = this.$loading({
          lock: true,
          text: '添加密码中',
          customClass: 'iconfont icon-jiazai2',
          background: 'rgba(0, 0, 0, .7)'
        })
        try {
          // 第一步获取密钥:参数加密传输
          const { data: enKey } = await this.$http.post('/ajshow/auth/getEncKey')
          if (!enKey.status) {
            loading.close()
            return this.$message.warning('初始化第一次连接')
          }
          const { data: res } = await this.$http.post('/ajshow/password/show', {
            id: Enc(this.passwordForm.id, enKey.data),
            phone: Enc(this.passwordForm.phone, enKey.data),
            code: Enc(this.passwordForm.verifyCode, enKey.data)
          })
          if (!res.status) {
            loading.close()
            return this.$message.error('获取密码失败')
          }
          this.$message.success('您的密码信息已发送至您的邮箱，请注意查收')
          this.show.passwordDialogVisible = false
        } catch (e) {
          this.$message.error(e.toString())
        }
        loading.close()
        this.show.passwordDialogVisible = false
      })
    }
  }
}
</script>

<style lang="less" scoped>
::v-deep .el-card__body{
  .cell{
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
  }
  .el-pagination--small{
    padding-top: 20px;
  }
}
</style>
